package com.cloudcreativity.blyg.sqlite.utils;

import android.content.Context;
import android.text.TextUtils;

import com.cloudcreativity.blyg.sqlite.Goods;
import com.cloudcreativity.blyg.sqlite.GoodsDao;

import java.util.List;

public class GoodsDaoUtils {
    private static final String TAG = AreaDaoUtils.class.getSimpleName();
    private DaoManager mManager;

    public GoodsDaoUtils(Context context) {
        mManager = DaoManager.getInstance();
        mManager.init(context);
    }

    public boolean insert(Goods goods){
        //先根据条码查询该商品是否存在
        Goods unique = mManager.getDaoSession().getGoodsDao().queryBuilder()
                .where(GoodsDao.Properties.BarCode.eq(goods.getBarCode()))
                .unique();
        if(null == unique){
            mManager.getDaoSession().getGoodsDao().insertOrReplace(goods);
            return true;
        }else{
            return false;
        }

    }

    public void update(Goods goods){
        mManager.getDaoSession().getGoodsDao().update(goods);
    }

    public void delete(Long id){
        mManager.getDaoSession().getGoodsDao().deleteByKey(id);
    }

    public List<Goods> queryByPage(int page,int size,long cateOneId,long cateTwoId,String key){
        if(TextUtils.isEmpty(key)){
            return mManager.getDaoSession().getGoodsDao()
                    .queryBuilder()
                    .where(GoodsDao.Properties.CategoryOneId.eq(cateOneId),
                            GoodsDao.Properties.CategoryTwoId.eq(cateTwoId))
                    .offset((page-1) * size)
                    .limit(size)
                    .list();
        }else{
            return mManager.getDaoSession().getGoodsDao()
                    .queryBuilder()
                    .where(GoodsDao.Properties.Name.like("%"+key+"%"))
                    .offset((page-1) * size)
                    .limit(size)
                    .list();
        }
    }

    public List<Goods> queryByKey(String key){
        try {
            return mManager.getDaoSession().getGoodsDao()
                    .queryBuilder()
                    .where(GoodsDao.Properties.Name.like("%"+key+"%"))
                    .list();
        }catch (Exception e){
            return null;
        }
    }

    public Goods queryByCode(String code){
        return mManager.getDaoSession().getGoodsDao()
                .queryBuilder()
                .where(GoodsDao.Properties.BarCode.eq(code))
                .unique();
    }

    public void updateStock(Long id,float amount){
        Goods goods = mManager.getDaoSession().getGoodsDao().loadByRowId(id);
        goods.setStock(goods.getStock()-amount);
        mManager.getDaoSession().update(goods);
    }


    public void insertAll(List<Goods> goods){
        mManager.getDaoSession().getGoodsDao()
                .insertOrReplaceInTx(goods,false);
    }

    public long count(){
        return mManager.getDaoSession().getGoodsDao()
                .count();
    }
}
